<script setup lang="ts">
import type { IEditorConfig, IToolbarConfig } from '@wangeditor/core';

import { onBeforeUnmount, shallowRef } from 'vue';

import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { message } from 'ant-design-vue';

import { uploadFileApi } from '#/api/app';

import '@wangeditor/editor/dist/css/style.css';
// 引入 css
interface RichTextEditorProps {
  platform?: string;
  path?: string;
}
const props = withDefaults(defineProps<RichTextEditorProps>(), {
  platform: '',
  path: '',
});
const valueHtml = defineModel<string>();
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
// 工具栏配置
const toolbarConfig: Partial<IToolbarConfig> = {};

// 编辑器配置
const editorConfig: Partial<IEditorConfig> = {
  // 进入页面不自动聚焦
  autoFocus: true,
  MENU_CONF: {},
};

// 封装 - 上传图片、视频
const uploadFile = async (type: string, file: any, insertFn: any) => {
  if (file.size / 1024 / 1024 > 50) {
    message.error(`文件大小不能超过50MB!`);
    return false;
  } else {
    // 这里根据自己的需求进行处理 --- S
    const result = await uploadFileApi(props.platform, props.path, file);
    insertFn(result.url, result.filename, result.filename);
  }
};

// 上传图片
// @ts-ignore
editorConfig.MENU_CONF.uploadImage = {
  async customUpload(file: any, insertFn: any) {
    uploadFile('1', file, insertFn);
  },
};

// 上传视频
// @ts-ignore
editorConfig.MENU_CONF.uploadVideo = {
  async customUpload(file: any, insertFn: any) {
    uploadFile('2', file, insertFn);
  },
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor === null) return;
  editor.destroy();
});

const handleCreated = (editor: any) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
  // 查看所有工具栏key
  // console.log(editor.getAllMenuKeys());
};
const onClear = () => {
  const editor = editorRef.value;
  editor.clear();
};
const setHtml = (value: any) => {
  const editor = editorRef.value;
  editor.setHtml(value);
};

defineExpose({
  onClear,
  setHtml,
});
</script>
<template>
  <div style="max-width: 600px; border: 1px solid #ccc">
    <!-- 工具栏 -->
    <Toolbar
      :default-config="toolbarConfig"
      :editor="editorRef"
      mode="default"
      style="border-bottom: 1px solid #ccc"
    />
    <!-- 内容部分   @onBlur="handleChange"   -->
    <Editor
      v-model="valueHtml"
      :default-config="editorConfig"
      mode="default"
      style="height: 450px; overflow-y: hidden"
      @on-created="handleCreated"
    />
  </div>
</template>

<style lang="scss" scoped>
:deep() .w-e-textarea-video-container {
  video,
  img {
    max-width: 787px;
  }
}
</style>
